﻿using App.Common;
using App.IService;
using App.Model;
using App.Service;
using App.WebAPI.Utilty._MD5;
using App.WebAPI.Utilty.ApiResult;
using AutoMapper;
using Microsoft.IdentityModel;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System.Security.Claims;
using Microsoft.Net.Http.Headers;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.AspNetCore.Authentication;
using Microsoft.VisualStudio.Services.Account;
using App.Model.DTO.User;
using SqlSugar;
using App.Model.DTO.Article;
using App.Model.Enum;
using System.Drawing.Printing;
using System.Linq.Expressions;
using static Microsoft.Extensions.Logging.EventSource.LoggingEventSource;
using System;
using Microsoft.VisualStudio.Services.UserAccountMapping;
using System.Net.Sockets;
using System.Net;

namespace WebAPI.Controllers
{
    [Route("[controller]/[Action]")]
    [ApiController]
    [Authorize] // 使用授权
    public class AccountInfoController : ControllerBase
    {

        private readonly ILogger<AccountInfoController> _logger;

        private IUserInfoService _iUserInfoService;
        private IRoleService _iRoleService;
        public AccountInfoController(ILogger<AccountInfoController> logger, IUserInfoService iUserIofoService, IRoleService iRoleService)
        {
            _logger = logger;
            _iUserInfoService = iUserIofoService;
            _iRoleService = iRoleService;
        }
        /// <summary>
        /// 添加用户
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> Create(CreateUserRequestInput req)
        {
            var id = GuidCombGenerator.GenerateCombGuid32();
            var role = await _iRoleService.FindAsync(req.RoleId);
            var isEnable = EnumUserIsEnableType.ENABLE;
            UserInfo user = new UserInfo
            {
                Id = id,
                UserName = req.UserName,
                NickName = req.NickName,
                //加密密码
                UserPassword = MD5Helper.MD5Encrypt32(req.Password),
                Email = req.Email,
                CreateAt = DateTime.Now,
                RoleId = req.RoleId,
                RoleType = role.RoleType,
                IsEnable = isEnable,
                UpdateAt = DateTime.Now
            };
            var oldUserName = await _iUserInfoService.FindAsync(c => c.UserName == req.UserName);
            var oldNickName = await _iUserInfoService.FindAsync(c => c.NickName == req.NickName);
            if (oldUserName != null) return ApiResultHelper.Error("账号已存在");
            if (oldNickName != null) return ApiResultHelper.Error("用户名已存在");
            bool b = await _iUserInfoService.CreateAsync(user);
            if (!b) return ApiResultHelper.Error("添加失败，服务器异常");
            return ApiResultHelper.Success(user, b);
        }
        /// <summary>
        /// 修改用户
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> UpdateUserInfo(UpdateUserInfoRequestInput req)
        {

            string id = req.Id;
            var userInfo = await _iUserInfoService.FindAsync(id);
            var role = await _iRoleService.FindAsync(req.RoleId);
            userInfo.UserName = req.UserName;
            userInfo.RoleId = req.RoleId;
            userInfo.RoleType = role.RoleType;
            userInfo.AvatarImage = req.AvatarImage;
            userInfo.NickName = req.NickName;
            userInfo.Email = req.Email;
            userInfo.Mobile = req.Mobile;
            userInfo.UpdateAt = DateTime.Now;
            var oldNickName = await _iUserInfoService.FindAsync(c => c.NickName == req.NickName);
            var oldEmail = await _iUserInfoService.FindAsync(c => c.Email == req.Email);
            if (oldNickName != null) return ApiResultHelper.Error("昵称已存在");
            if (oldEmail != null) return ApiResultHelper.Error("邮箱已存在");
            bool b = await _iUserInfoService.EditAsync(userInfo);
            if (!b) return ApiResultHelper.Error("修改失败，服务器异常");
            return ApiResultHelper.Success(userInfo, b);
        }

        /// <summary>
        /// 修改头像
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> UpdateAvatar([FromForm] IFormFile file)
        {
            string id = User.FindFirst(ClaimTypes.Name).Value;
            ////当前程序路径
            var path = Directory.GetCurrentDirectory();
            var webRootPath = "http://api.mengblog.cn";
            var fileName = Guid.NewGuid().ToString() + Path.GetExtension(file.FileName);
            var filePath = Path.Combine(path, "wwwroot/image", fileName);

            using (var stream = System.IO.File.Create(filePath))
            {
                await file.CopyToAsync(stream);
            }

            var userAvatar = await _iUserInfoService.FindAsync(id);
            userAvatar.AvatarImage = webRootPath + "/image/" + fileName;
            userAvatar.UpdateAt = DateTime.Now;
            bool b = await _iUserInfoService.EditAsync(userAvatar);
            if (!b) return ApiResultHelper.Error("修改失败，服务器异常");
            return ApiResultHelper.Success(userAvatar.AvatarImage, b);
        }
        /// <summary>
        /// 修改密码
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> UpdatePassword(UpdateUserPasswordRequestInput req)
        {
            string id = User.FindFirst(ClaimTypes.Name).Value;
            string newPwd = MD5Helper.MD5Encrypt32(req.NewPassword);
            string password = MD5Helper.MD5Encrypt32(req.Password);
            var userPassword = await _iUserInfoService.FindAsync(id);
            if (password != userPassword.UserPassword) return ApiResultHelper.Error("旧密码输入错误");
            userPassword.UserPassword = newPwd;
            userPassword.UpdateAt = DateTime.Now;
            bool b = await _iUserInfoService.EditAsync(userPassword);
            if (!b) return ApiResultHelper.Error("修改失败，服务器异常");
            return ApiResultHelper.Success("修改成功", b);
        }

        /// <summary>
        /// 修改角色
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> UpdateRole(UpdateUserRoleRequestInput req)
        {
            if (string.IsNullOrEmpty(req.RoleId))
            {
                return ApiResultHelper.Error("参数不能为空");
            };

            string id = User.FindFirst(ClaimTypes.Name).Value;
            var userRole = await _iUserInfoService.FindAsync(id);
            userRole.RoleId = req.RoleId;
            userRole.RoleType = req.RoleType;
            userRole.UpdateAt = DateTime.Now;
            bool b = await _iUserInfoService.EditAsync(userRole);
            if (!b) return ApiResultHelper.Error("修改失败，服务器异常");
            return ApiResultHelper.Success("修改成功", b);
        }
        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="req"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ActionResult<ApiResult>> Delete(DeleteUserRequestInput req)
        {
            bool b = await _iUserInfoService.DeleteAsync(req.Id);
            if (!b) return ApiResultHelper.Error("删除失败,服务器发生错误");
            return ApiResultHelper.Success(null, b);
        }

        /// <summary>
        /// 当前用户信息
        /// </summary>
        /// <param name="iMapper"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpGet]
        public async Task<ApiResult> CurrentUserInfo([FromServices] IMapper iMapper)
        {

            var id = User.FindFirst(ClaimTypes.Name).Value;
            if (string.IsNullOrEmpty(id))
            {
                return ApiResultHelper.NoAuthorization("登录已过期，请重新登录");
            }
            var userInfo = await _iUserInfoService.FindAsync(id);
            try
            {
                var userDTO = iMapper.Map<UserDTO>(userInfo);
                return ApiResultHelper.Success(userDTO,true);
            }
            catch
            {
                return ApiResultHelper.Error("服务器异常");
            }
        }
        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <param name="iMapper"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult<ApiResult>> GetAllUser([FromServices] IMapper iMapper)
        {

            var data = await _iUserInfoService.QueryAsync();
            if (data.Count == 0) return ApiResultHelper.Error("没有更多用户");
            try
            {
                var userDTO = iMapper.Map<List<UserDTO>>(data);
                return ApiResultHelper.Success(userDTO, data.Count, true);
            }
            catch (Exception)
            {
                return ApiResultHelper.Error("服务器异常");
            }
        }
        /// <summary>
        /// 用户列表分页查询
        /// </summary>
        /// <param name="iMapper"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult> GetPageList([FromBody] PageRequest req, [FromServices] IMapper iMapper)
        {
            RefAsync<int> total = 0;
            Expression<Func<UserInfo, bool>> func = u => true;
            List<UserInfo> user = null;
            if (!string.IsNullOrEmpty(req.Filter))
            {
                func = u => u.UserName.Contains(req.Filter) || u.NickName.Contains(req.Filter) || u.Email.Contains(req.Filter) || u.Mobile.Contains(req.Filter);
            }
            if (req.PageIndex == 1 && req.PageSize == int.MaxValue)
            {
                var allUsers = func != null ? await _iUserInfoService.QueryAsync(func) : await _iUserInfoService.QueryAsync();
                total = allUsers.Count;
                user = allUsers;
            }
            else
            {
                user = await _iUserInfoService.QueryAsync(func ?? (u => true), req.PageIndex, req.PageSize, total);
            }
            try
            {
                var userDTO = iMapper.Map<List<UserDTO>>(user);
                return ApiResultHelper.Success(userDTO, total, true);
            }
            catch (Exception)
            {
                return ApiResultHelper.Error("服务器异常");
            }
        }
        [HttpGet]
        public IActionResult Get()
        {
            string ipAddress = Request.HttpContext.Connection.RemoteIpAddress?.ToString();
            if (ipAddress == null)
            {
                return NotFound("IP address not found");
            }
            return Ok(ipAddress);
        }
    }
}
